<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-12
 * Time: 9:09
 */

namespace app\common\logic;
use app\common\logic\Logic;
use app\common\model\Mall;
use app\common\model\MallSpec;
use app\common\model\Company;
class MallLogic extends Logic
{
    protected $modelClass = 'app\common\model\Mall';
    protected $column = 'id,user_id,status,catid,co_type_id';
    

    
    public function addGoods($params){
        
        $modelClass = 'app\common\model\Goods';
        $goods = new $modelClass();
        $rt = $goods->allowField(true)->save($params);
        
        
        $modelClass2 = 'app\common\model\GoodsData';
        $data = new $modelClass2();
        $post['goods_id'] = $goods->id;
        $post['content'] = $params['content'];
        $data->allowField(true)->save($post);
        
        return $goods->id;
    }
    
    public function addsGoodsAttr($post){
        
        $modelClass = 'app\common\model\GoodsAttr';
        $model = new $modelClass();
        $ids = $model->allowField(true)->saveAll($post);
        return $ids?$ids:false;

    }
    
    public function addsSpec($post){
        $this->modelClass = 'app\common\model\MallSpec';
        $rt = $this->adds($post);
        return $rt;
        
    }
    
    public function getStock($id){
        $mall = Mall::get($id);
        if(!$mall){
            exception('不存在id为'.$id.'的商品');
        }
        return $mall->stock;
    }
    
    /**
     * @desc 修改库存
     * @param $id 对应的mallid
     * @param $minus 为true减少,为false增加。可能商家会有增加的操作。。。
     * @param $number
     */
    public function changeStock($id,$minus,$number){
        $mall = Mall::get($id);
        if(!$mall){
            exception('不存在id为'.$id.'的商品');
        }
        
        $symbol = $minus?-1:1;//决定增加还是减少
        
        if($number>$mall->stock&&$symbol==-1){
            exception($mall['id'].'库存不足');
        }
        
        $mall->stock += $symbol*$number;
        $mall->isUpdate()->save();
        return true;
        
    }
    
    public function getMallSpec($mallId){
        $mall = $this->findModel($mallId);
        return $mall->specs;
    }
    
}